//
//  AppDelegate.m
//  IntimateGift
//
//  Created by 蔡宏业 on 14/12/17.
//  Copyright (c) 2014年 蔡宏业. All rights reserved.
//

#import "AppDelegate.h"
#import "ChoicenessViewController.h"
#import "LeftViewController.h"
#import "MMExampleDrawerVisualStateManager.h"
#import "MMDrawerBaseNavigationViewController.h"
#import "UIViewController+MMDrawerController.h"
//#import <ShareSDK/ShareSDK.h>
//#import "WeiboApi.h"
#import "WeiboSDK.h"

@interface AppDelegate () <WeiboSDKDelegate>
//

@property (nonatomic,strong)MMDrawerController * drawerController;

@property (nonatomic,retain) UIView *nigView;
@property (nonatomic, retain) UIImageView *nightImage;

@end

@implementation AppDelegate


- (void)dealloc
{
    [_window release];
    [_mine release];
    [_nightImage release];
    [_nigView release];
    [_wbCurrentUserID release];
    [_wbtoken release];
    [_mine release];
    [super dealloc];
}


#pragma mark 设置抽屉
- (BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
    
    
    
    // 左边
    LeftViewController * leftSideDrawerViewController = [[LeftViewController alloc] init];
    
//    // 右边
//    RightViewController * rightSideDrawerViewController = [[RightViewController alloc] init];
    
    // 中间
    ChoicenessViewController * choicenessVC = [[ChoicenessViewController alloc] init];
    
    MMDrawerBaseNavigationViewController * navigationController = [[MMDrawerBaseNavigationViewController alloc] initWithRootViewController:choicenessVC];
    
    [navigationController setRestorationIdentifier:@"MMExampleCenterNavigationControllerRestorationKey"];
    
    if(OSVersionIsAtLeastiOS7()){
//        MMDrawerBaseNavigationViewController * rightSideNavController = [[MMDrawerBaseNavigationViewController alloc] initWithRootViewController:rightSideDrawerViewController];
//        [rightSideNavController setRestorationIdentifier:@"MMExampleRightNavigationControllerRestorationKey"];
//        MMDrawerBaseNavigationViewController * leftSideNavController = [[MMDrawerBaseNavigationViewController alloc] initWithRootViewController:leftSideDrawerViewController];
        [leftSideDrawerViewController setRestorationIdentifier:@"MMExampleLeftNavigationControllerRestorationKey"];
        self.drawerController = [[MMDrawerController alloc]
                                 initWithCenterViewController:navigationController leftDrawerViewController:leftSideDrawerViewController];
        [self.drawerController setShowsShadow:NO];
    }
    else{
        self.drawerController = [[MMDrawerController alloc]
                                 initWithCenterViewController:navigationController leftDrawerViewController:leftSideDrawerViewController];
    }
    [self.drawerController setRestorationIdentifier:@"MMDrawer"];
//    [self.drawerController setMaximumRightDrawerWidth:200.0];
    [self.drawerController setMaximumLeftDrawerWidth:140.0];
    
    [self.drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeAll];
    [self.drawerController setCloseDrawerGestureModeMask:MMCloseDrawerGestureModeAll];
    
    
    
    [self.drawerController
     setDrawerVisualStateBlock:^(MMDrawerController *drawerController, MMDrawerSide drawerSide, CGFloat percentVisible) {
         MMDrawerControllerDrawerVisualStateBlock block;

         if(block){
             block(drawerController, drawerSide, percentVisible);
         }
     }];
    
    
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    if(OSVersionIsAtLeastiOS7()){
        UIColor * tintColor = [UIColor colorWithRed:29.0/255.0
                                              green:173.0/255.0
                                               blue:234.0/255.0
                                              alpha:1.0];
        [self.window setTintColor:tintColor];
    }
    
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    [self.window setRootViewController:self.drawerController];
    
    // 微博登陆
    [WeiboSDK enableDebugMode:YES];
    [WeiboSDK registerApp:@"3837244365"];
    
    
    return YES;
}

//- (void)initializePlat
//{
//    /**
//     连接新浪微博开放平台应用以使用相关功能，此应用需要引用SinaWeiboConnection.framework
//     http://open.weibo.com上注册新浪微博开放平台应用，并将相关信息填写到以下字段
//     **/
//    [ShareSDK connectSinaWeiboWithAppKey:@"3837244365"
//                               appSecret:@"062453705bcef2181ac8fc6fb013993d"
//                             redirectUri:@"http://open.weibo.com"];
//}

// 初始化
- (instancetype)init
{
    self = [super init];
    if (self) {
        // 观察者
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        [center addObserver:self selector:@selector(receiveNotifica:) name:@"heiyejianglin" object:nil];
        // 观察者
        NSNotificationCenter *center2 = [NSNotificationCenter defaultCenter];
        [center2 addObserver:self selector:@selector(receiveNotifica2:) name:@"limingjianglin" object:nil];
        
    }
    return self;
}


#pragma mark 夜间模式动画
- (void)receiveNotifica:(NSNotification *)center
{
    
    
    //1.UIView动画
    [UIView animateWithDuration:0.6 animations:^{
        
        self.nightImage.frame = CGRectMake(self.window.bounds.size.width * 26.66 / 100, self.window.bounds.size.height * 36.73 / 100, self.window.bounds.size.width * 60.1 / 100, self.window.bounds.size.width * 46.66 / 100);
        self.nigView.hidden = NO;
//                self.nightImage.frame = CGRectMake(self.window.bounds.size.width, self.window.bounds.size.height * 36.73 / 100, self.window.bounds.size.width * 46.66 / 100, self.window.bounds.size.height * 26.23 / 100);
//        
//                UIImage *image = [UIImage imageNamed:@"sun5.png"];
//                self.nightImage.image = image;
        
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [UIView animateWithDuration:0.5 animations:^{
            
            self.nightImage.frame = CGRectMake(self.window.bounds.size.width, self.window.bounds.size.height * 36.73 / 100, self.window.bounds.size.width * 60 / 100, self.window.bounds.size.height * 46.66 / 100);
        }];
    });
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        UIImage *image = [UIImage imageNamed:@"sun5.png"];
        self.nightImage.image = image;
        
        
    });
    
    
}

- (void)receiveNotifica2:(NSNotification *)center
{
    
    
    // UIView动画
    [UIView animateWithDuration:0.6 animations:^{
        
        self.nightImage.frame = CGRectMake(self.window.bounds.size.width * 26.66 / 100, self.window.bounds.size.height * 36.73 / 100, self.window.bounds.size.width * 46.66 / 100,  self.window.bounds.size.width * 46.66 / 100);
        
        
        
    }];
    // 延时调用动画
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [UIView animateWithDuration:0.5 animations:^{
            
            self.nightImage.frame = CGRectMake(- self.window.bounds.size.width, self.window.bounds.size.height * 36.73 / 100, self.window.bounds.size.width * 46.66 / 100, self.window.bounds.size.height * 46.66 / 100);
            self.nigView.hidden = YES;
        }];
        
    });
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        UIImage *image = [UIImage imageNamed:@"moon2.png"];
        self.nightImage.image = image;
        
    });
    
    
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    //1.初始化ShareSDK应用,字符串"iosv1101"是应该换成你申请的ShareSDK应用中的Appkey
//    [ShareSDK registerApp:@"4dfebf3f783c"];
    
    //2. 初始化社交平台
    //2.1 代码初始化社交平台的方法
//    [self initializePlat];
    
    //2.2 使用后台管理初始社交平台的方法
    //    [self initializePlatForTrusteeship];
    
    //3.设置根视图控制器，如果没有使用storyboard一定要设置。
    
    
//    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    
    
    // 夜间模式view
    self.nigView = [[UIView alloc] initWithFrame:self.window.bounds];
    self.nigView.userInteractionEnabled = NO;
    self.nigView.hidden = YES;
    self.nigView.backgroundColor = [UIColor blackColor];
    self.nigView.alpha = 0.6;
    [self.window addSubview:self.nigView];
    [_nigView release];
    
    self.nightImage = [[UIImageView alloc] initWithFrame:CGRectMake(- self.window.bounds.size.width, self.window.bounds.size.height * 36.73 / 100, self.window.bounds.size.width * 46.66 / 100, self.window.bounds.size.height * 26.23 / 100)];
    UIImage *nigImage = [UIImage imageNamed:@"moon2.png"];
    self.nightImage.image = nigImage;
    [self.window addSubview:self.nightImage];
    [_nightImage release];
    
    [NSThread sleepForTimeInterval:1];
    
    
    
    // Override point for customization after application launch.
    return YES;
}

#pragma mark 设置微博
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    return [WeiboSDK handleOpenURL:url delegate:self];
    
    
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return [WeiboSDK handleOpenURL:url delegate:self];
    
}

#pragma mark 微博网络请求
- (void)didReceiveWeiboResponse:(WBBaseResponse *)response
{
    if ([response isKindOfClass:WBSendMessageToWeiboResponse.class])
    {
        // 分享认证
        NSString *title = NSLocalizedString(@"发送结果", nil);
        NSString *message = [NSString stringWithFormat:@"%@: %d\n%@: %@\n%@: %@", NSLocalizedString(@"响应状态", nil), (int)response.statusCode, NSLocalizedString(@"响应UserInfo数据", nil), response.userInfo, NSLocalizedString(@"原请求UserInfo数据", nil),response.requestUserInfo];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                        message:message
                                                       delegate:nil
                                              cancelButtonTitle:NSLocalizedString(@"确定", nil)
                                              otherButtonTitles:nil];
        WBSendMessageToWeiboResponse* sendMessageToWeiboResponse = (WBSendMessageToWeiboResponse*)response;
        NSString* accessToken = [sendMessageToWeiboResponse.authResponse accessToken];
        if (accessToken)
        {
            self.wbtoken = accessToken;
        }
        NSString* userID = [sendMessageToWeiboResponse.authResponse userID];
        if (userID) {
            self.wbCurrentUserID = userID;
        }
//        [alert show];
        [alert release];
    }
    else if ([response isKindOfClass:WBAuthorizeResponse.class])
    {
        // 登陆认证
        NSString *title = NSLocalizedString(@"认证结果", nil);
        NSString *message = [NSString stringWithFormat:@"%@: %d\nresponse.userId: %@\nresponse.accessToken: %@\n%@: %@\n%@: %@", NSLocalizedString(@"响应状态", nil), (int)response.statusCode,[(WBAuthorizeResponse *)response userID], [(WBAuthorizeResponse *)response accessToken],  NSLocalizedString(@"响应UserInfo数据", nil), response.userInfo, NSLocalizedString(@"原请求UserInfo数据", nil), response.requestUserInfo];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                        message:message
                                                       delegate:nil
                                              cancelButtonTitle:NSLocalizedString(@"确定", nil)
                                              otherButtonTitles:nil];
        
        self.wbtoken = [(WBAuthorizeResponse *)response accessToken];
        self.wbCurrentUserID = [(WBAuthorizeResponse *)response userID];
//        [alert show];
        [alert release];
        NSLog(@"%@", self.wbtoken);
        
        NSString * str = [NSString stringWithFormat:@"https://api.weibo.com/2/users/show.json?uid=%@&access_token=%@",self.wbCurrentUserID,self.wbtoken];
        str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//        NSLog(@"-----%@", str);
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:str] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];
        request.HTTPMethod = @"GET";
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//            NSLog(@"%@", result);
            
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:result,@"key", nil];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"tamenlaile" object:@"香皂" userInfo: dic];
            
            
        }];
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"登陆成功" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
        [alertView release];
        
        
    }
}

#pragma mark 抽屉导航
- (UIViewController *)application:(UIApplication *)application viewControllerWithRestorationIdentifierPath:(NSArray *)identifierComponents coder:(NSCoder *)coder
{
    NSString * key = [identifierComponents lastObject];
    if([key isEqualToString:@"MMDrawer"]){
        return self.window.rootViewController;
    }
    else if ([key isEqualToString:@"MMExampleCenterNavigationControllerRestorationKey"]) {
        return ((MMDrawerController *)self.window.rootViewController).centerViewController;
    }
//    else if ([key isEqualToString:@"MMExampleRightNavigationControllerRestorationKey"]) {
//        return ((MMDrawerController *)self.window.rootViewController).rightDrawerViewController;
//    }
    else if ([key isEqualToString:@"MMExampleLeftNavigationControllerRestorationKey"]) {
        return ((MMDrawerController *)self.window.rootViewController).leftDrawerViewController;
    }
    else if ([key isEqualToString:@"MMExampleLeftSideDrawerController"]){
        UIViewController * leftVC = ((MMDrawerController *)self.window.rootViewController).leftDrawerViewController;
        if([leftVC isKindOfClass:[UINavigationController class]]){
            return [(UINavigationController*)leftVC topViewController];
        }
        else {
            return leftVC;
        }
        
    }
//    else if ([key isEqualToString:@"MMExampleRightSideDrawerController"]){
//        UIViewController * rightVC = ((MMDrawerController *)self.window.rootViewController).rightDrawerViewController;
//        if([rightVC isKindOfClass:[UINavigationController class]]){
//            return [(UINavigationController*)rightVC topViewController];
//        }
//        else {
//            return rightVC;
//        }
//    }
    return nil;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
